<template>
  <div>
    <el-form ref="form" label-width="80px">
      <el-form-item label="SPU名称">{{spu.spuName}}</el-form-item>
      <el-form-item label="SKU名称">
        <el-input placeholder="sku名称" v-model="skuInfo.skuName"></el-input>
      </el-form-item>
      <el-form-item label="价格(元)">
        <el-input placeholder="价格(元)" type="number" v-model="skuInfo.price"></el-input>
      </el-form-item>
      <el-form-item label="重量(千克)">
        <el-input placeholder="重量(千克)" v-model="skuInfo.weight"></el-input>
      </el-form-item>
      <el-form-item label="规格描述">
        <el-input type="textarea" row="4" placeholder="规格描述" v-model="skuInfo.skuDesc"></el-input>
      </el-form-item>
      <el-form-item label="平台属性">
        <el-form :inline="true" ref="form" label-width="80px">
          <el-form-item :label="attr.attrName" v-for="attr in spuAttrInfoList" :key="attr.id" style="margin-bottom: 7px">
            <el-select placeholder="请选择" v-model="attr.attrIdAndValueId" >
              <el-option
                :label="attrValue.valueName"
                :value="`${attr.id}:${attrValue.id}`"
                v-for="attrValue in attr.attrValueList"
                :key="attrValue.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form :inline="true" ref="form" label-width="80px">
          <el-form-item
            :label="saleAttr.saleAttrName"
            v-for="saleAttr in spuSaleAttrList"
            :key="saleAttr.id"
          >
            <el-select placeholder="请选择" v-model="saleAttr.attrIdAndValueId">
              <el-option
                :label="saleAttrValue.saleAttrValueName"
                :value="`${saleAttr.id}:${saleAttrValue.id}`"
                v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                :key="saleAttrValue.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="图片列表">
        <el-table style="width: 100%" border :data="spuImageList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="80"></el-table-column>
          <el-table-column prop="prop" label="图片" width="width">
            <template slot-scope="{row}">
              <el-image style="width: 80px; height: 80px" :src="row.imgUrl"></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="imgName" label="名称" width="width"></el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{row}">
              <el-button type="primary" size="mini" v-if="row.isDefault == 0" @click="changeDefault(row)">设置默认</el-button>
              <el-button type="success" size="mini" v-else>默认</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'SkuForm',
  data () {
    return {
      // 服务器返回的图片数据
      spuImageList: [],
      // 服务器返回的销售属性
      spuSaleAttrList: [],
      // 服务器返回的平台属性
      spuAttrInfoList: [],
      spu: {},
      // 收集选中的图片的数据字段
      imgList: [],

      // 收集sku表单的数据，将来要带给服务器的。格式是后端定义好的。
      skuInfo: {
        // 第一大类：父组件给的数据
        category3Id: '',
        spuId: 0,
        tmId: 0,
        // 第二大类：需要在skuForm中收集的数据
        price: 0,
        skuName: '',
        weight: '',
        skuDesc: '',
        // 第三大类：数据需要自己写代码收集
        skuDefaultImg: '',
        skuAttrValueList: [
          {
            attrId: 0,
            valueId: 0,
          },
        ],
        skuImageList: [
          // {
          //   id: 0,
          //   imgUrl: '',
          //   isDefault: '',
          //   skuId: 0,
          //   spuImgId: 0,
          // },
        ],
        skuSaleAttrValueList: [
          // {
          //   id: 0,
          //   saleAttrId: 0,
          //   saleAttrName: '',
          //   saleAttrValueId: 0,
          //   saleAttrValueName: '',
          //   skuId: 0,
          //   spuId: 0,
          // },
        ],
      },
    }
  },
  methods: {
    // 请求这个页面所需的数据
    async getData (category1Id, category2Id, category3Id, spu) {
      // 收集父组件给的数据
      this.skuInfo.category3Id = category3Id;
      this.skuInfo.tmId = spu.tmId;
      this.skuInfo.spuId = spu.id;
      this.spu = spu;
      // 获取图片数据的请求
      let result_imageList = await this.$API.spu.reqSpuImageList(spu.id);
      // console.log(result_imageList);
      if (result_imageList.code == 200) {
        let list = result_imageList.data;
        list.forEach(element => {
          // 为获取到的每个图片都添加一个isDefault字段
          element.isDefault = 0;
        });
        this.spuImageList = list;
      }
      // 获取销售属性数据的请求
      let result_saleAttrList = await this.$API.spu.reqSpuSaleAttrList(spu.id);
      // console.log(result_saleAttrList);
      if (result_saleAttrList.code == 200) {
        this.spuSaleAttrList = result_saleAttrList.data;
      }
      // 获取平台属性数据的请求
      let result_saleAttrInfoList = await this.$API.spu.reqAttrInfoList(category1Id, category2Id, category3Id);
      // console.log(result_saleAttrInfoList)
      if (result_saleAttrInfoList.code == 200) {
        this.spuAttrInfoList = result_saleAttrInfoList.data;
      }
    },
    // table表格复选框按钮的事件回调
    handleSelectionChange(params){
      // 获取到用户选中图片的信息数据，但是注意当前收集的数据当中缺少isDefault字段，所以先收集到imgList中
      // 然后发请求之前进行参数整理
      // console.log(params);
      this.imgList = params;
    },
    // 改变设置默认和默认按钮的切换
    changeDefault(row){
      // 排他操作：只有点击了的isDefault字段变为1，其他的都变为0
      this.spuImageList.forEach(item=> item.isDefault = 0)
      row.isDefault = 1;
      // 收集默认图片地址
      this.skuInfo.skuDefaultImg = row.imgUrl;
    },
    // 点击取消按钮的回调
    cancel(){
      this.$emit('change_Scene');
      // 清空数据
      Object.assign(this._data, this.$options.data());
    },
    // 点击保存按钮的回调
    async save(){
      // 整理所需的参数
      // 平台属性参数整理
      const {spuAttrInfoList, skuInfo, spuSaleAttrList, imgList} = this;
      // 把之前收集到的id整理一下
      let arr = []
      spuAttrInfoList.forEach(item=>{
        if(item.attrIdAndValueId){
          const [attrId, valueId] = item.attrIdAndValueId.split(':');
          arr.push({attrId, valueId})
        }
        // 将全部attrId和valueId的对象数组扔给服务器需携带的参数中
        skuInfo.skuAttrValueList = arr;
      })

      // 整理销售属性
      skuInfo.skuSaleAttrValueList = spuSaleAttrList.reduce((prev,item)=>{
        if(item.attrIdAndValueId){
          const [saleAttrId, saleAttrValueId] = item.attrIdAndValueId.split(':');
          prev.push({saleAttrId, saleAttrValueId})
        }
        return prev
      },[])
      
      // 整理图片数据
      skuInfo.skuImageList = imgList.map(item=>{
        return {
          imgName: item.imgName,
          imgUrl: item.imgUrl,
          isDefault: item.isDefault,
          spuImgId: item.id
        }
      })

      // 数据都整理完毕该发请求了
      let result = await this.$API.spu.reqAddSku(skuInfo)
      // console.log(result);
      if(result.code == 200){
        this.$message({type:'success', message: '保存成功'})
        // 通知父组件切换场景spuList
        this.$emit('change_Scene')
      }
    }
  }

}
</script>

<style lang="less" scoped>
</style>